package com.example.home.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.persistence.Access;
import javax.sql.DataSource;
import java.util.zip.DataFormatException;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.jdbcAuthentication().dataSource(dataSource)
               /*.usersByUsernameQuery("SELECT username,password enabled"+"FROM users WHERE username = ?")
               .authoritiesByUsernameQuery("SELECT username,authority " + "FROM authorities WHERE username = ?");*/
               .withDefaultSchema()
               .passwordEncoder(bCryptPasswordEncoder)
               //教师账户
               .withUser("su")
               .password("123")
               .roles("USER")

               .and()
               .withUser("yin")
               .password("123")
               .roles("USER")

               //管理员账户
               .and()
               .withUser("admin")
               .password("123")
               .roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                /*
                .antMatchers("/cate/new").hasRole("ADMIN")
                .antMatchers("/cate/save").hasRole("ADMIN")
*/

                .antMatchers("/","/**").permitAll()
             /*   .antMatchers("/collages/new").hasRole("ADMIN")
                .antMatchers("/courses/new").hasRole("ADMIN")
                .antMatchers("/students/new").hasRole("ADMIN")
                .antMatchers("/teachers/new").hasRole("ADMIN")
                .antMatchers("/majors/new").hasRole("ADMIN")*/
                .and()
                .formLogin().loginPage("/logins");
               // .antMatchers("/").authenticated().and().formLogin();

              /*  http.csrf().disable();
                http.headers().frameOptions().disable();*/


    }
}
